package com.test.seataaccount.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.seataaccount.dao.AccountDao;
import com.test.seataaccount.entity.Account;
import com.test.seataaccount.service.AccountService;
import io.seata.common.util.NumberUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountDao, Account> implements AccountService {

    @Resource
    private AccountDao accountDao;

    public void decrease(Long userId, BigDecimal money) {
        log.info("------->seata-account-samples中扣减账户余额开始-------<");

        // 模拟超时异常，全局事务回滚
        try {
            Thread.sleep(30*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Account account = accountDao.selectOne(new QueryWrapper<Account>().lambda().eq(Account::getUserId,userId));
        if (account == null){
            return;
        }

        account.setResidue(NumberUtil.add(account.getResidue().doubleValue(),money.doubleValue()));
        accountDao.updateById(account);

        log.info("------->seata-account-samples中扣减账户余额结束-------<");
    }
}
